<template>
  <div class="article-page">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>面经后台</el-breadcrumb-item>

      <el-breadcrumb-item>面经管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card shadow="never" border="false">
      <template #header>
        <div class="header">
          <span>共 {{ total }} 条记录</span>

          <el-button
            @click="optHandler('add')"
            icon="el-icon-plus"
            size="small"
            type="primary"
            round
          >
            添加面经
          </el-button>
        </div>
      </template>

      <!-- el-table -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="stem" label="标题" width="400">
        </el-table-column>
        <el-table-column prop="creator" label="作者"> </el-table-column>
        <el-table-column prop="likeCount" label="点赞"> </el-table-column>
        <el-table-column prop="views" label="浏览数"> </el-table-column>
        <el-table-column prop="createdAt" label="更新时间"> </el-table-column>
        <el-table-column label="操作" width="120">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <div class="actions">
              <i
                class="el-icon-view"
                @click="optHandler('view', scope.row)"
              ></i>
              <i
                class="el-icon-edit-outline"
                @click="optHandler('edit', scope.row)"
              ></i>
              <i
                class="el-icon-delete"
                @click="optHandler('del', scope.row)"
              ></i>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        background
        layout="prev, pager, next"
        :total="1000"
        :current-page="current"
        @current-change="changePage"
      >
      </el-pagination>
    </el-card>

    <!-- 抽屉 -->
    <el-drawer
      title="新增面经"
      :visible.sync="isShowDrawer"
      direction="rtl"
      size="60%"
    >
      <!-- 查看面经 -> 只需要普通的html元素来回显数据即可 -->
      <div v-if="optType === 'view'" class="article-preview">
        <h5>{{ form.stem }}</h5>

        <!-- v-html用来解析富文本的内容，让用户查看带有样式的内容，就有整体的排版了 -->
        <div v-html="form.content"></div>
      </div>

      <!-- 表单 -->
      <el-form
        v-else
        :model="form"
        :rules="rules"
        ref="form"
        label-width="80px"
      >
        <el-form-item label="标题" prop="stem">
          <el-input placeholder="输入面经标题" v-model="form.stem"></el-input>
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <quill-editor
            v-model="form.content"
            @blur="$refs.form.validateField('content')"
          ></quill-editor>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submit">确认</el-button>

          <el-button>取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
import {
  getArticleList,
  createArticle,
  getArticleDetail,
  updateArticle,
  removeArticle
} from "@/api/article";
// require styles
// 导入富文本组件的css和组件对象
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

import { quillEditor } from "vue-quill-editor";

export default {
  name: "article-page",
  components: {
    quillEditor, //局部注册组件
  },
  data() {
    return {
      artId: 0,
      optType: "",
      form: {
        stem: "", // 标题
        content: "这是标题", //富文本内容
      },
      isShowDrawer: false, // true:显示抽屉  false:关闭抽屉
      total: 0,
      current: 1,
      tableData: [
        // {
        //   id: 1,
        //   stem: "广东紫云平台数据服务有限公司前端面经，未通过",
        //   createdAt: "2022-01-20 00-00-00",
        //   creator: "中二苏北陌",
        //   likeCount: 1,
        //   views: 32,
        // },
      ],
      rules: {
        stem: [{ required: true, message: "请输入面经标题", trigger: "blur" }],
        content: [
          { required: true, message: "请输入面经标题", trigger: "blur" },
          { min: 20, message: "面经内容至少20个长度", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    async submit() {
      try {
        // 1. 表单的合法性检查
        await this.$refs.form.validate();

        // 处理各种逻辑(新增和编辑是共用同一个表单)
        if (this.optType === "add") {
          // 调用方法
          await createArticle(this.form);
          this.$message.success("新增成功");
          this.isShowDrawer = false;
          // 刷新当前列表
          this.current = 1; //将当前页码重置为1，才能拿到最新的数据
          this.getList();
        } else if (this.optType === "edit") {
          // 收集表单最新数据，发送请求给服务器完整修改，重新刷新页面并关闭抽屉
          // 由于this.form缺失了id,所以需要补齐
          this.form.id = this.artId;
          await updateArticle(this.form);
          this.$message.success("修改成功");
          this.current = 1;
          this.getList();
          this.isShowDrawer = false;
        }
      } catch (error) {
        console.log(error);
      }
    },
    // 操作函数
    async optHandler(type, row) {
      this.optType = type;
      this.artId = row && row.id;

      // 1. 判断type==='add'打开抽屉
      if (type === "add") {
        this.isShowDrawer = true;
      } else if (type === "edit" || type === "view") {
        // 编辑逻辑 -> 根据id，获取老数据，回显到页面上，打开抽屉
        let id = row.id;
        
        let res = await getArticleDetail(id);
        // 回显到页面上-> this.form赋值
        this.form.stem = res.data.stem;
        this.form.content = res.data.content;

        this.isShowDrawer = true;
      } else {
        // 删除
        // 1. 提示用户确认删除吗？
        try {
          await this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          });

          // 2. 确定 -> 发请求给服务器执行数据的真正删除逻辑
          await removeArticle(this.artId)
          this.$message.success("删除成功");
          this.getList();  
         
        } catch (error) {
          console.log(error);
          
          // this.$message({
          //   type: "info",
          //   message: "已取消删除",
          // });
        }

        // this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        //   confirmButtonText: "确定",
        //   cancelButtonText: "取消",
        //   type: "warning",
        // })
        //   .then(() => {
        //     this.$message({
        //       type: "success",
        //       message: "删除成功!",
        //     });
        //   })
        //   .catch(() => {
        //     this.$message({
        //       type: "info",
        //       message: "已取消删除",
        //     });
        //   });
        // 2. 确定 -> 发请求给服务器执行数据的真正删除逻辑
        // 3. 提示用户删除成功，并且刷新页面数据
      }
      console.log(type, row);
    },

    // 定义一个分页组件的当前页码切换的函数
    changePage(currentPage) {
      console.log(currentPage);
      this.current = currentPage;

      this.getList();
    },
    // 2. 请求服务器数据
    async getList() {
      let res = await getArticleList({ current: this.current, pageSize: 5 });
      // console.log(res.data)
      // 3. 给tableData赋值自动筛选页面
      this.tableData = res.data.rows;
      this.total = res.data.total;
    },
  },
};
</script>

<style lang="scss" scoped>
.el-card {
  margin-top: 25px;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-right: 16px;
  }
  .actions {
    font-size: 18px;
    display: flex;
    justify-content: space-around;
    color: #666;
    > i:hover {
      color: rgba(114, 124, 245, 1);
      cursor: pointer;
    }
  }
}
.el-pagination {
  margin-top: 20px;
  text-align: center;
}
.el-breadcrumb {
  margin-top: 10px;
}
.el-form {
  padding-right: 40px;
}
.quill-editor {
  ::v-deep .ql-editor {
    height: 300px;
  }
}
.el-rate {
  padding: 10px 0;
}
.article-preview {
  padding: 0 40px 40px 40px;
  > h5 {
    font-size: 20px;
    color: #666;
    border-bottom: 1px dashed #ccc;
    padding-bottom: 30px;
    margin: 0 0 20px 0;
  }
}
</style>
